# -*- coding: iso-8859-2 -*-

from authorshipanalyzer.authorslot import AuthorSlot
from authorshipanalyzer.file import ResourceReader
from authorshipanalyzer.slot import Slot

class CategoryFiller:
    '''
    Assign category relative frequencies to author slots
    '''
    
    def __init__(self, dir = "categories_weighted"):
        '''
        @param: categoryCounter: dict<category, number_of_messages_assigned_to_category>
        '''
        self.categoryCounter = {}
        
        reader = ResourceReader()
        categoryNames = reader.getMechanizmFilesDict(dir).keys()
        categoryNames.append("computers")
        categoryNames.append("education")
        
        for category in categoryNames:
            self.categoryCounter[category] = 0.0
    
    def fill(self, authorSlots):
        '''
        Fill author categories with (author category counter) / (overall category counter)
        '''        
        
        # Count overall category appearances
        for authorSlot in authorSlots.values():
            for slot in authorSlot.slots:
                for category in slot.category:
                    self.categoryCounter[category] += 1.0
#                    print "mianownik: category %s counter %f" % (category, self.categoryCounter[category])
        
        # Foreach author slot            
        for authorSlot in authorSlots.values():
            
            # Create category dict
            authCategoryCounter = {}
            for category in self.categoryCounter.keys():
                authCategoryCounter[category] = 0.0
            
            # Create author frequency dict    
            for slot in authorSlot.slots:
                for category in slot.category:
                    authCategoryCounter[category] += 1.0
#                    print "author %s category %s counter %f" % (slot.author, category, authCategoryCounter[category])
                    
            # Divide author counter by overall counter
            for category, sum in self.categoryCounter.items():
                if sum > 0.0:
                    authCategoryCounter[category] = float(authCategoryCounter[category] / sum)
#                    print "category %s counter %f" % (category, authCategoryCounter[category])
                
            authorSlot.categories = authCategoryCounter
            
        for category in self.categoryCounter.keys():
            self.categoryCounter[category] = 0.0